(function($){
    function getPluginName(target){
        if ($(target).data('treegrid')){
            return 'treegrid';
        } else {
            return 'datagrid';
        }
    }
    var extendedOptions = {
		userAppSearch: true,//是否使用公共的查询方法
		formId: '',//使用公共的查询方法时，对应的表单Id
		isSetStorage: true,//使用公共的查询方法时，是否缓存本地缓存中
        defaultFilterOptions: {
            onInit: function(target){
                var name = getPluginName(target);
                var opts = $(target)[name]('options');
                var filterOpts = this.filterOptions;
                var field = $(this).attr('name');
                var input = $(this);
				input.focus(function(){
					nowFilterTable = target;
				});
                var control = $(this);
                var control_optsMode =  true;
                if(filterOpts.type == 'combo' || filterOpts.type == 'combobox' || filterOpts.type == 'combotree' || filterOpts.type == 'combogrid' || filterOpts.type == 'combotreegrid'){
                    var control_opts = control[filterOpts.type]('options');
                    var onClick = null;
                    var onChange=null;
                    var filter = null;
                    if(control_opts.mode){
                        control_optsMode = false;
                    }
                    if(typeof control_opts.onClick == 'function'){
                        onClick = control_opts.onClick;

                    }
                    if(typeof control_opts.onChange == 'function'){
                        onChange = control_opts.onChange;

                    }
                    if(typeof control_opts.filter == 'function'){
                        filter = control_opts.filter;

                    }
                    control[filterOpts.type]({
                        onClick: function(newValue, oldValue){
                            nowFilterTable = target;
                            if(typeof onClick == 'function') {
                                onClick.call(control,newValue, oldValue);
                            }
                        },
                        onChange: function(newValue, oldValue){
                            nowFilterTable = target;
                            if (this.timer){
                                clearTimeout(this.timer);
                            }
                            if (opts.filterDelay){
                                this.timer = setTimeout(function(){
                                    _doFilter();
                                }, opts.filterDelay);
                            } else {
                                _doFilter();
                            }
                            if(typeof onChange == 'function') {
                                onChange.call(control,newValue, oldValue);
                            }
                        },
                        filter:function(q, row){
                            var opts = control.combobox('options');
                            return row[opts.textField].indexOf(q)!= -1 ;
                        }
                    });
                    control.parent().find("input[type='text']").bind('keydown.filter',function (e) {
                        $(target)[name]('doFilter');
                    })
                } else if(filterOpts.type == 'datebox' || filterOpts.type == 'datetimebox') {
					var control_opts = control[filterOpts.type]('options');
					var onChange=null;
					var filter = null;
					if(control_opts.mode){
					    control_optsMode = false;
					}
					if(typeof control_opts.onChange == 'function'){
					    onChange = control_opts.onChange;
					
					}
					if(typeof control_opts.filter == 'function'){
					    filter = control_opts.filter;
					
					}
					control[filterOpts.type]({
					    onChange: function(newValue, oldValue){
							nowFilterTable = target;
							if (this.timer){
								clearTimeout(this.timer);
							}
							if (opts.filterDelay){
								this.timer = setTimeout(function(){
									_doFilter();
								}, opts.filterDelay);
							} else {
								_doFilter();
							}
					        if(typeof onChange == 'function') {
					            onChange.call(control,newValue, oldValue);
					        }
					    }
					});
				}
                if (input.data('textbox')){
                    input = input.textbox('textbox');
                }
                if(filterOpts.options && filterOpts.options.value){
                    $(target)[name]('addFilterRule', {
                        field: field,
                        //op: op,
                        value: filterOpts.options.value
                    });
                }
                input.unbind('.filter').bind('input.filter keydown', function(e){
                    nowFilterTable = target;
                    if(control_optsMode) {
                        var t = $(this);
                        if (this.timer) {
                            clearTimeout(this.timer);
                        }
                        if (e.keyCode == 13) {
                            _doFilter();
                        } else if (opts.filterDelay) {
                            this.timer = setTimeout(function () {
                                _doFilter();
                            }, opts.filterDelay);
                        }
                    }
                });
                function _doFilter(){
                    var rule = $(target)[name]('getFilterRule', field);
                    var value;
                    if(filterOpts.type == 'text' || filterOpts.type == 'textbox'|| filterOpts.type == 'numberbox'){
                        value = input.val();
						if(typeof value == "object") value = control[filterOpts.type]("getValue");
                    } else {
                        value = control[filterOpts.type]("getValue");
                    }
                    if (value != '') {
                        if ((rule && rule.value != value) || !rule) {
                            var op = rule ? rule.op : (filterOpts ? filterOpts.defaultFilterOperator || opts.defaultFilterOperator : opts.defaultFilterOperator);
                            $(target)[name]('addFilterRule', {
                                field: field,
                                // op: opts.defaultFilterOperator,
                                op: op,
                                value: value
                            });
							if(opts.userAppSearch){
								App.search($(target).attr("id"),opts.formId,opts.isSetStorage);
								return;
							}
                            if(opts.automaticPolling !== false)
                                $(target)[name]('doFilter');
                        }
                    } else {
                        if (rule) {
                            $(target)[name]('removeFilterRule', field);
							if(opts.userAppSearch){
								App.search($(target).attr("id"),opts.formId,opts.isSetStorage);
								return;
							}
                            if(opts.automaticPolling !== false)
                                $(target)[name]('doFilter');
                        }
                    }
                }
            }
        }
    };
    $.extend($.fn.datagrid.defaults, extendedOptions);
    $.extend($.fn.treegrid.defaults, extendedOptions);
	
	//拖动列宽的处理
	function dragCol(options){
		if(typeof options == "string" || !options) return;
		$(this).parent().find(".datagrid-header-row td").each(function(){
			var resizable = $(this).find('div[resizable="false"]');
			if(resizable.length) {
				$(this).attr("resizable",false);
			}
		});
	}
	
	//执行前设置
	function beforeSetting(options,param){
		if(typeof options == "string" || !options || !$(this).parent()[0]) {
			return;
		}
		//调用公共查询默认配置
		options.filterDelay = 0;
		options.userAppSearch = true;
		options.isSetStorage = true;
	}
	//执行后设置
	function afterSetting(options,param){
		if(typeof options == "string" && options == "enableFilter"){
			//设置重置按钮
			var name = getPluginName(this);
			var opts = $(this)[name]('options');
			var div = null;
			var filed = "";
			if(opts.rownumbers) filed = "_";
			else if(opts.isRightFixed && opts.frozenColumns && opts.frozenColumns[0] && opts.frozenColumns[0][0]) filed = opts.frozenColumns[0][0].field;
			else if(opts.isRightFixed && opts.columns && opts.columns[0] && opts.columns[0][0]) filed = opts.columns[0][0].field;
			else if(!opts.isRightFixed && opts.frozenColumns && opts.frozenColumns[0] && opts.frozenColumns[0][0]) filed = opts.frozenColumns[0][0].field;
			else if(!opts.isRightFixed && opts.columns && opts.columns[0] && opts.columns[0][0]) filed = opts.columns[0][0].field;
			if(filed) {
				var div = $(this).parent().find('.datagrid-filter-row td[field="' + filed + '"]');
				if(div.find(".table-btn.btn-reset").length) div = null;
			}
			if(div) {
				div.css("text-align","center");
				var resetBtn = $('<a class="table-btn btn-reset">重置</a>');
				resetBtn.click(function(){
					App.reset($(this).attr("id"),opts.formId,opts.isSetStorage);
				})
				div.html(resetBtn);
			}
			
		}
		dragCol.call(this,options);
	}
	var datagrid = $.fn.datagrid;
	$.fn.datagrid = function(options, param){
		beforeSetting.call(this,options);
		var res = datagrid.call(this,options, param);
		afterSetting.call(this,options);
		return res;
	}
	$.fn.datagrid = Object.assign($.fn.datagrid,datagrid);
	
	var treegrid = $.fn.treegrid;
	$.fn.treegrid = function(options, param){
		beforeSetting.call(this,options,param);
		var res = treegrid.call(this,options, param);
		afterSetting.call(this,options,param);
		return res;
	}
	$.fn.treegrid = Object.assign($.fn.treegrid,treegrid);
	
	
	$.fn.progressbar.defaults.isShowProgress = false;
})(jQuery);

$.extend(App,{
	
	/**
	 * 表单子表删除
	 * @param tableId 子表标签id值
	 * @param baseUrl 表数据的添加baseUrl
	 * @param callback 删除成功后回调
	 * @param isInv 是否软删除
	 */
	sublistDel: function (tableId, baseUrl,callback,isInv) {
		if(isInv !== false) isInv = true;
	    var $this = this;
	    var rows = $("#" + tableId).datagrid("getChecked");
		rows = [].concat(rows);
	    if (rows.length > 0) {
	        $.messager.confirm("数据删除警告", "请确认是否删除数据？", function (result) {
	            if (result) {
	                $this.sublistDelByAjax(tableId, baseUrl, rows,callback,isInv);
	            } else {
	                result = false;
	            }
	            return result;
	        });
	    } else {
	        $.messager.alert("提示", '请必须选择一项进行删除', "warning");
	    }
	},
	/**
	 * 多行数据删除
	 * @param url 删除url
	 * @param isDelBack 是否删除的判断回调方法
	 * @param callback 删除成功后的回调方法
	 * @param tableId 表格id
	 * @param formId 表单Id
	 * @param isInv 是否软删除
	 */
	batchDelete: function (url, isDelBack, callBack, tableId, formId,isInv) {
		if(isInv !== false) isInv = true;
	    if (!url) {
	        url = isInv ? "invalid" : "batchDelete";
	    }
	    if (!tableId) tableId = "table";
	    var rows = $("#" + tableId).datagrid("getChecked");
	    if (rows.length > 0) {
	        $.messager.confirm("数据删除警告", "请确认是否删除数据？", function (boo) {
	            if (boo) {
	                App.blockUI({
	                    boxed: true,
	                    message: "处理中..."
	                });
	                var delData = [];
	                for (var i = 0; i < rows.length; i++) {
	                    var boo = true;
	                    if (isDelBack) {
	                        boo = isDelBack(rows[i]);
	                    }
	                    if (boo !== false) {
	                        delData.push(rows[i].mid);
	                    }
	                }
	                if (delData.length == 0) {
	                    App.unblockUI();
	                    // $.messager.alert("提示", "没有一项通过可删除验证！", "warning");
						toastr["warning"]("没有一项通过可删除验证！", "提示");
	                    return;
	                }
					App.multipleToastrCallBack = function(){
						if (callBack) {
						    callBack();
						} else {
						    App.search(formId, tableId);
						}
					}
	                App.postJson(url, delData, function (result) {
	                    App.unblockUI();
						toastr["success"]("删除成功!", "提示");
						if (callBack) {
						    callBack();
						} else {
						    App.search(formId, tableId);
						}
	                }, function (error) {
	                    App.unblockUI();
	                    // $.messager.alert("删除失败", error, "error");
						toastr["error"](error, "删除失败");
	                })
	            }
	        });
	    } else {
	        // $.messager.alert("提示", "请至少选择一项数据！", "warning");
			toastr["warning"]("请至少选择一项数据！", "提示");
	    }
	},
},{
	tableSearch:{},//表格模糊查询条件缓存
	
	
	/**
	 * 查询
	 * @param tableId 要更新的表Id
	 * @param formId 表单名称
	 * @param isSetStorage 是否缓存本地缓存中
	 */
	search: function (tableId, formId, isSetStorage) {
	    if (!formId) formId = 'searchForm';
	    if (!tableId) tableId = 'table';
	    var searchForm = [];
	    if ($("#" + formId).length > 0) {
	        searchForm = $('#' + formId).serializeArray();
	    }
	    var filterRules = this.filterRules[tableId] || [];
	    if (filterRules && filterRules.length > 0) {
	        for (var i = 0; i < filterRules.length; i++) {
	            for (var j = 0; j < searchForm.length; j++) {
	                if (searchForm[j].name == filterRules[i].field) {
	                    if (searchForm[j].value) {
	                        filterRules[i].value = searchForm[j].value;
	                        $('#' + tableId).datagrid('addFilterRule', filterRules[i]);
	                    } else {
	                        $('#' + tableId).datagrid('removeFilterRule', filterRules[i].field);
	                    }
	                    break;
	                }
	            }
	        }
	    }
	    $("#" + tableId).datagrid("doFilter"); //更新表格
	    if (isSetStorage !== false) {
	        this.setTableSearch(tableId, formId);
	    }
	},
	
	/**
	 * 查询输入框重置
	 * @param tableId 要更新的表Id
	 * @param formId 表单名称
	 * @param isSetStorage 是否缓存本地缓存中
	 */
	reset: function (tableId, formId, isSetStorage) {
	    if (!formId) formId = 'searchForm';
	    if (!tableId) tableId = 'table';
	    var filterRules = this.filterRules[tableId] || [];
	    for (var i = 0; i < filterRules.length; i++) {
	        $('#' + tableId).datagrid('removeFilterRule', filterRules[i].field);
	    }
	    $('#' + tableId).datagrid("removeFilterRule");
	    $('#' + tableId).datagrid("doFilter"); //更新表格
	    if ($("#" + formId).length > 0) {
	        $("#" + formId).form({});
	        $("#" + formId).form("clear");
	    }
	    if (isSetStorage !== false) {
	        this.setTableSearch(tableId, formId);
	    }
	},
	/**
	 * 批量导出台账数据
	 * @param tableId
	 * @param url
	 */
	export: function (tableId, formId, url) {
	    if (!tableId) tableId = "table";
	    if (!formId) formId = "searchForm";
	    if (!url) url = "export";
	    var data = this.getTableSearch(tableId, formId).queryParams;
	    App.batchExport(url, data);
	},
	/**
	 * 表格缓存
	 * @param tableId
	 * @param formId
	 */
	setTableSearch: function (tableId,formId) {
		if (!formId) formId = 'searchForm';
		if (!tableId) tableId = 'table';
		var key = "table_" + tableId + formId,
			filterRules = App.filterRules[tableId] || [],
			searchData = {};
		if($("#" + formId).length > 0){
			key += "_form_" + formId;
			var searchForm = $('#' + formId).serializeArray();
			if (filterRules && filterRules.length > 0) {
				for (var i = 0; i < filterRules.length; i++) {
					for (var j = 0; j < searchForm.length; j++) {
						if (searchForm[j].name == filterRules[i].field) {
							if(searchForm[j].value){
								searchData[searchForm[j].name] = searchForm[j].value;
							}
							filterRules[i].value = searchForm[j].value;
							break;
						}
					}
				}
			}
		}
		var opts = $("#" + tableId).datagrid("options");
		if($("#" + tableId).data('treegrid')){
			opts = $("#" + tableId).treegrid("options");
		}
		if(opts.filterRules && opts.filterRules.length > 0) {
			for (var i = 0; i < opts.filterRules.length; i++) {
				var boo = true;
				for(var j = 0; j < filterRules.length; j++){
					if(opts.filterRules[i].field == filterRules[j].field){
						boo = false;
						break;
					}
				}
				if(boo){
					filterRules.push(opts.filterRules[i]);
					searchData[opts.filterRules[i].field] = opts.filterRules[i].value;
				}
			}
		}

		key += window.location.pathname;
		this.tableSearch[key] = {
			searchData: searchData,
			queryParams: {
				page: opts.pageNumber||1,
				rows: opts.pageSize,
				filterRules: opts.filterStringify(filterRules)
			}
		};
	},
	/**
	 * 表格缓存获取
	 * @param tableId
	 * @param formId
	 * @returns {{}|any}
	 */
	getTableSearch: function (tableId,formId) {
		if (!formId) formId = 'searchForm';
		if (!tableId) tableId = 'table';
		var key = "table_" + tableId + formId;
		if($("#" + formId).length > 0){
			key += "_form_" + formId;
		}
		key += window.location.pathname;
		var item = this.tableSearch[key];
		if(item){
			return item;
		}
		return {
			searchData:{},
			queryParams: {}
		};
	},
});

var $sessionUserId = "";
(function($){
	//解决飞书电子试验或者流程编辑时打开浏览器窗口没有权限，需要重新登录的问题
	let openCall = window.open;
	window.open = function(...params){
		if($sessionUserId){
			params[0] = '/public/forward/forward.html?userId=' + $sessionUserId + '&url=' + encodeURIComponent(params[0]);
		}
		return openCall.apply(this,params);
	}
})(jQuery);